package com.taikang.hmp.hbusiness.doctor.register.action.intface;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taikang.hmp.frame.common.AxisClient;
import com.taikang.hmp.frame.common.ErrorConstant;
import com.taikang.hmp.frame.common.TKException;
import com.taikang.hmp.frame.common.datastructre.Dto;
import com.taikang.hmp.frame.common.datastructre.support.BaseDto;
import com.taikang.hmp.frame.common.datastructre.support.ResponseDto;
import com.taikang.hmp.frame.common.properties.PropertiesHelper;
import com.taikang.hmp.frame.common.tools.MD5Util;
import com.taikang.hmp.frame.common.tools.SmsUtils;
import com.taikang.hmp.frame.common.tools.json.JsonHelper;
import com.taikang.hmp.frame.common.web.action.BaseAction;
import com.taikang.hmp.frame.common.web.mobilecheck.MobileCheckBean;
import com.taikang.hmp.frame.common.web.mobilecheck.MobileCheckFactory;
import com.taikang.hmp.frame.common.web.remotecall.security.uidlimit.AppUidStatusFactory;
import com.taikang.hmp.frame.common.web.session.AppSessionFactory;
import com.taikang.hmp.frame.common.web.session.SessionBean;
import com.taikang.hmp.frame.user.bean.AuthUserInfo;
import com.taikang.hmp.hbusiness.doctor.register.service.ILoginService;


/**
 * 类说明 :
 * 
 * @author :sym
 * @time : 2015-9-29 下午3:20:17
 */
public class LoginAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private static Logger logger = LoggerFactory.getLogger(LoginAction.class);

	private ILoginService loginService;

	public ILoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(ILoginService loginService) {
		this.loginService = loginService;
	}

	public String executeAction() {
		if ("regist".equals(requestDto.getMethod())) {
			return regist();
		} else if ("login".equals(requestDto.getMethod())) {
			return login();
		} else if ("identityWhenReg".equals(requestDto.getMethod())) {
			return identify(requestDto.getMethod());
		} else if ("identityWhenReset".equals(requestDto.getMethod())) {
			return identify(requestDto.getMethod());
		} else if ("identityWhenReg1".equals(requestDto.getMethod())) {
			return identifyWithInterval(requestDto.getMethod());
		} else if ("identityWhenReset1".equals(requestDto.getMethod())) {
			return identifyWithInterval(requestDto.getMethod());
		}else if ("passreset".equals(requestDto.getMethod())) {
			return passreset();
		}else if ("passreset1".equals(requestDto.getMethod())) {
			return passreset1();
		} else {
			throw new TKException("no support method:" + requestDto.getMethod());
		}
	}
	
	/**
	 * 注册
	 */
	private String regist() {
		boolean error = false;
		logger.info("--------------------------开始用户注册");
		ResponseDto responseDto = new ResponseDto();
		
		//获取参数
		requestDto.setSessionid("");
		requestDto.setUid("");
		Dto paramDto = requestDto.getRequestlist().get(0);
		paramDto = super.appendRequestBase(paramDto, requestDto);
		String requestsource = requestDto.getRequestsource();
		//邀请码
		String invitationCode = paramDto.getAsString("invitation_code").toUpperCase();
		
		//手机号验证
		if(loginService.check_mobile_repeat(paramDto.getAsString("mobile"))){
			logger.info("-----------------------该手机号已注册！");
			error = true;
			responseDto.addErrorCode(ErrorConstant.HD_REGIST_OCUPATION);//占有
		}

		JSONObject pmdata = null;
		
		
		//校验工号信息
		if(!error){
			String url = PropertiesHelper.appHelper.getValue("ucmurl");  
			String json = "{'branchtype':'"+invitationCode.substring(0, 2)+"','agntcoy':'"+invitationCode.substring(2, 3)+"','agentcode':'"+invitationCode.substring(3, invitationCode.length())+"'}";
			logger.error(System.currentTimeMillis()+" 请求UCMJSON:"+json);
			String ret = AxisClient.call(url,"agentByCode",json);
			logger.error(System.currentTimeMillis()+"UCM返回JSON:"+ret);
			pmdata = JSONObject.fromObject(ret);
			logger.info("UCM返回:"+pmdata.getString("errmessage"));
			if(!"Y".equalsIgnoreCase(pmdata.getString("result"))){
				error = true;
				responseDto.addErrorInfo(ErrorConstant.HD_UCM_FAIL,pmdata.getString("errmessage"));
			}else if("其它".equalsIgnoreCase(pmdata.getString("agentstate"))){
				error = true;
				responseDto.addErrorInfo(ErrorConstant.HD_NOT_WORK,"非在职人员");
			}
		}
		if(error){
			super.setDataMap(responseDto);
			return SUCCESS;
		}
		
		//校验验证码功能，放在所有校验之后，因为验证码校验正确后立即失效
		boolean isRightCode = MobileCheckFactory.getInstance(
				requestDto.getRequestsource()).checkCode(
				paramDto.getAsString("mobile"), paramDto.getAsString("code"));
		
		if(!isRightCode){
			logger.error("*********:验证码错误！验证码："+paramDto.getAsString("code"));
			responseDto.addErrorCode(ErrorConstant.HD_IDENTIFYCODE_NOT_EXIST);
			super.setDataMap(responseDto);
			return SUCCESS;
		}
		
		String uid = null;
		String customerid = null;
		if(!error){
			Dto dto = loginService.saveRegistInfo(paramDto);
			uid = dto.getAsString("uid");
			customerid = dto.getAsString("customerid");
			logger.info("-----------------------保存注册信息成功！uid:"+uid+"|customerid:"+customerid);
		}
		
		//保存ucm返回的代理人信息  测试阶段注释 上线打开
		pmdata.put("customerid", customerid);
		pmdata.put("invitationCode", invitationCode);
		loginService.saveUcmInfo(pmdata);
		
		//保存session
		if(StringUtils.isNotEmpty(uid)){
			//保存用户状态
			SessionBean sessionInfo = loginService.getCustomerBasicInfo(uid);
			String sessionId = AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionInfo);
			AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginSuccess(uid,requestsource);
			responseDto.setSessionid(sessionId);
			responseDto.setUid(uid);
		}else{
			//保存用户状态
			AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginFail(uid,requestsource);
			responseDto.addErrorCode(ErrorConstant.HD_USER_NOT_EXIST);
		}
		super.setDataMap(responseDto);
		logger.info("response json:"+JsonHelper.formatJson(responseDto.toJson()));
		return SUCCESS;
	}
	
	/**
	 * 获取手机验证码
	 * add by wangfugang
	 */
	private String identifyWithInterval(String type) {
		boolean error  = false;
		ResponseDto responseDto = new ResponseDto();
		
		requestDto.setSessionid("");
		requestDto.setUid("");
		Dto paramDto = requestDto.getRequestlist().get(0);
		
		//
		String mobile = paramDto.getAsString("mobile");
		
		if("identityWhenReg1".equalsIgnoreCase(type)){
			if(loginService.check_moblie_exist(mobile)){
				logger.info(mobile+"存在，不可以注册");
				error = true;
				responseDto.addErrorCode(ErrorConstant.HD_MOBILE_IS_EXISTS);
			}
			if(error){
				super.setDataMap(responseDto);
				return SUCCESS;
			}
		}else if("identityWhenReset1".equalsIgnoreCase(type)){
			if(!loginService.check_moblie_exist(mobile)){
				logger.info(mobile+"不存在，不发送验证码");
				error = true;
				responseDto.addErrorCode(ErrorConstant.HD_MOBILE_IS_NOT_EXISTS);
			}
			if(error){
				super.setDataMap(responseDto);
				return SUCCESS;
			}
		}else{
			throw new TKException("not support method:"+type);
		}
		//同一手机号发送短信时间间隔小于1分钟
		MobileCheckBean mb = MobileCheckFactory.getInstance(requestDto.getRequestsource()).getMobileBean(mobile);
		if(mb != null)
		{
			Date lastEffectDate = mb.getLastEffectDate();
			Date now_date = new Date();
			long lastEffectTime = lastEffectDate.getTime();
			long nowTime = now_date.getTime();			
			int subSeconds = (int)(nowTime-lastEffectTime)/1000;
			int intervalSeconds = PropertiesHelper.getSendsmsIntervalSeconds();
			logger.info("配置短信发送间隔时间："+intervalSeconds);
			logger.info("实际短信发送间隔时间："+subSeconds);
			if(subSeconds <= intervalSeconds){
				error = true;
				responseDto.addErrorCode(ErrorConstant.SEND_SMS_FREQUENTLY);
				logger.error("同一手机号发送短信时间间隔小于1分钟！");
			}
		}
		
		if(!error){
			if(StringUtils.isNotEmpty(mobile)){
				String code = MobileCheckFactory.getInstance(requestDto.getRequestsource()).produceIdentifyCode(mobile);			
				String pattern = PropertiesHelper.appHelper.getValue("message.passreset.pattern");
				String msg = pattern.replace("code", code);
				//发送短信
				SmsUtils.sendSms(mobile, msg);
				logger.info("验证码:"+code);
				Dto dto = new BaseDto();
//				dto.put("identity", code);
				responseDto.pushResultDto(dto);
			}else{
				responseDto.addErrorCode(ErrorConstant.HD_MOBILE_IS_NULL);
			}
		}
		super.setDataMap(responseDto);
		return SUCCESS;
	}	
	
	/**
	 * 获取手机验证码
	 */
	private String identify(String type) {
		boolean error  = false;
		ResponseDto responseDto = new ResponseDto();
		
		requestDto.setSessionid("");
		requestDto.setUid("");
		Dto paramDto = requestDto.getRequestlist().get(0);
		
		//
		String mobile = paramDto.getAsString("mobile");
		
		if("identityWhenReg".equalsIgnoreCase(type)){
			if(loginService.check_moblie_exist(mobile)){
				logger.info(mobile+"存在，不可以注册");
				error = true;
				responseDto.addErrorCode(ErrorConstant.HD_MOBILE_IS_EXISTS);
			}
			if(error){
				super.setDataMap(responseDto);
				return SUCCESS;
			}
		}else if("identityWhenReset".equalsIgnoreCase(type)){
			if(!loginService.check_moblie_exist(mobile)){
				logger.info(mobile+"不存在，不发送验证码");
				error = true;
				responseDto.addErrorCode(ErrorConstant.HD_MOBILE_IS_NOT_EXISTS);
			}
			if(error){
				super.setDataMap(responseDto);
				return SUCCESS;
			}
		}else{
			throw new TKException("not support method:"+type);
		}
		
		if(!error){
			if(StringUtils.isNotEmpty(mobile)){
				String code = MobileCheckFactory.getInstance(requestDto.getRequestsource()).produceIdentifyCode(mobile);			
				String pattern = PropertiesHelper.appHelper.getValue("message.passreset.pattern");
				String msg = pattern.replace("code", code);
				//发送短信
				SmsUtils.sendSms(mobile, msg);
				logger.info("验证码:"+code);
				Dto dto = new BaseDto();
				dto.put("identity", code);
				
				responseDto.pushResultDto(dto);
			}else{
				responseDto.addErrorCode(ErrorConstant.HD_MOBILE_IS_NULL);
			}
		}
		super.setDataMap(responseDto);
		return SUCCESS;
	}
	
	
	
	/**
	 * 忘记密码
	 */
	private String passreset() {
		//通用校验
		ResponseDto responseDto = new ResponseDto();
			
		//获取参数
		requestDto.setSessionid("");
		requestDto.setUid("");
		Dto paramDto = requestDto.getRequestlist().get(0);
		Dto info = loginService.updateUserPwd(paramDto);
		
		String requestsource =  requestDto.getRequestsource();
		String mobile = (String)paramDto.get("mobile");

		if (!"0".equals(info.getAsString("mobileExist"))) {
			Dto dto = new BaseDto();
			dto.put("mobile", info.getAsString("mobile"));
			List<Dto> ld = new ArrayList<Dto>();
			ld.add(dto);
			responseDto.setResultlist(ld);

			// 保存session
			String uid = info.getAsString("uid");
			SessionBean sessionInfo = loginService.getCustomerBasicInfo(uid);
			String sessionId = AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionInfo);
			// 保存用户状态
			AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginSuccess(uid, requestsource);
			//
			responseDto.setSessionid(sessionId);
			responseDto.setUid(uid);
		} else {
			responseDto.addErrorCode(ErrorConstant.HD_MOBILE_IS_NOT_EXISTS);
		}
		super.setDataMap(responseDto);
		return SUCCESS;
	}
	
	/**
	 * 忘记密码
	 */
	private String passreset1() {
		//通用校验
		ResponseDto responseDto = new ResponseDto();
			
		//获取参数
		requestDto.setSessionid("");
		requestDto.setUid("");
		Dto paramDto = requestDto.getRequestlist().get(0);
		Dto info = loginService.updateUserPwd(paramDto);
		
		String requestsource =  requestDto.getRequestsource();
		String mobile = (String)paramDto.get("mobile");
		
		//校验验证码功能，放在所有校验之后，因为验证码校验正确后立即失效
		boolean isRightCode = MobileCheckFactory.getInstance(
				requestDto.getRequestsource()).checkCode(
				paramDto.getAsString("mobile"), paramDto.getAsString("code"));
		
		if(!isRightCode){
			logger.error("*********:验证码错误！验证码："+paramDto.getAsString("code"));
			responseDto.addErrorCode(ErrorConstant.HD_IDENTIFYCODE_NOT_EXIST);
			super.setDataMap(responseDto);
			return SUCCESS;
		}

		if (!"0".equals(info.getAsString("mobileExist"))) {
			Dto dto = new BaseDto();
			dto.put("mobile", info.getAsString("mobile"));
			List<Dto> ld = new ArrayList<Dto>();
			ld.add(dto);
			responseDto.setResultlist(ld);

			// 保存session
			String uid = info.getAsString("uid");
			SessionBean sessionInfo = loginService.getCustomerBasicInfo(uid);
			String sessionId = AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionInfo);
			// 保存用户状态
			AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginSuccess(uid, requestsource);
			//
			responseDto.setSessionid(sessionId);
			responseDto.setUid(uid);
		} else {
			responseDto.addErrorCode(ErrorConstant.HD_MOBILE_IS_NOT_EXISTS);
		}
		super.setDataMap(responseDto);
		return SUCCESS;
	}
	
	/**
	 * 登录
	 */
	private String login() {
		//通过校验
		ResponseDto responseDto = new ResponseDto();
		
		//参数的获取
		requestDto.setSessionid("");
		requestDto.setUid("");
		Dto paramDto = requestDto.getRequestlist().get(0);
		//手机号+密码
		String mob = paramDto.getAsString("mobile");
		String pwd = paramDto.getAsString("password");
		String requestsource = requestDto.getRequestsource();
		//登录
		List<AuthUserInfo> info = loginService.getLoginInfo(mob);
		if(info.size()>0){
			String userid = info.get(0).getUser_id();
			if(pwd.equals(info.get(0).getUser_pwd())){
				SessionBean sessionInfo = loginService.getCustomerBasicInfo(userid);
				String sessionId = AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionInfo);
				//保存用户状态
				AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginSuccess(userid,requestsource);
				responseDto.setSessionid(sessionId);
				responseDto.setUid(info.get(0).getUser_id());
				//是否激活 (0:激活；1：未激活)
				String is_act = "1";
				String act_code = sessionInfo.getCustomerInfo().getActivation_code();
				if(act_code != null){
					is_act = "0";
				}
				Dto dto = new BaseDto();
				dto.put("is_act", is_act);
				String checkStr = requestDto.getRequestid()+is_act;
				dto.put("checkStr", MD5Util.stringMD5(checkStr));
				responseDto.pushResultDto(dto);
			}else{
				//保存用户状态
				AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginFail(userid,requestsource);
				responseDto.addErrorCode(ErrorConstant.HD_PASSWORD_ERR);
			}
		}else{
			//保存用户状态
			responseDto.addErrorCode(ErrorConstant.HD_USER_NOT_EXIST);
		}
		super.setDataMap(responseDto);
		return SUCCESS;
	}
	
	
	

}
